<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>论文检测小助手</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --rococo-pink: #F8E1E4;
            --rococo-blue: #E1E8F0;
            --rococo-green: #E8F0E1;
            --rococo-gold: #D4AF37;
            --rococo-purple: #E8E1F0;
            --rococo-text: #6B4E71;
            --rococo-shadow: rgba(107, 78, 113, 0.1);
            --base-background: rgba(255, 255, 255, 0.85);
            --border-color: rgba(107, 78, 113, 0.2);
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, var(--rococo-pink) 0%, var(--rococo-blue) 100%);
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
        }
        
        body::before {
            content: '';
            position: absolute;
            width: 200%;
            height: 200%;
            background-image: 
                radial-gradient(circle at 25% 25%, var(--rococo-shadow) 1px, transparent 1px),
                radial-gradient(circle at 75% 75%, var(--rococo-shadow) 1px, transparent 1px);
            background-size: 50px 50px;
            opacity: 0.3;
            animation: backgroundMove 60s linear infinite;
            z-index: 0;
        }

        @keyframes backgroundMove {
            0% { transform: translate(0, 0); }
            100% { transform: translate(-50px, -50px); }
        }

        .main-container {
            display: flex;
            flex: 1;
            padding: 20px;
            gap: 20px;
            position: relative;
            z-index: 1;
            overflow: hidden;
            max-height: calc(100vh - 70px); /* Header height */
        }
        
        .panel {
            background: var(--base-background);
            border-radius: 15px;
            box-shadow: 0 5px 20px var(--rococo-shadow);
            backdrop-filter: blur(10px);
            border: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .left-panel {
            width: 40%;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .panel-header {
            font-size: 1.2em;
            font-weight: 600;
            color: var(--rococo-text);
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .panel-header::before {
            content: '✧';
            color: var(--rococo-gold);
        }

        .upload-section {
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.5);
        }

        .upload-section:hover {
            border-color: var(--rococo-gold);
            background-color: rgba(212, 175, 55, 0.05);
        }
        
        .file-list, .file-detail-view {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
            padding-right: 10px; /* for scrollbar */
        }

        .file-list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .file-list-title {
            font-size: 1em;
            font-weight: 600;
            color: var(--rococo-text);
        }

        .refresh-btn {
            background: none;
            border: 1px solid var(--border-color);
            color: var(--rococo-text);
            cursor: pointer;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .refresh-btn:hover {
            background: rgba(212, 175, 55, 0.1);
            border-color: var(--rococo-gold);
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border: 1px solid transparent;
            border-bottom: 1px solid var(--border-color);
            margin-bottom: -1px;
            transition: all 0.3s;
            cursor: pointer;
        }

        .file-item:hover, .file-item.active {
            background-color: rgba(212, 175, 55, 0.05);
            border-color: var(--rococo-gold);
            border-radius: 8px;
            transform: scale(1.02);
        }

        .file-info {
            flex: 1;
            color: var(--rococo-text);
        }

        .file-name {
            font-weight: 500;
        }

        .file-meta {
            font-size: 12px;
            opacity: 0.7;
        }
        
        .file-action-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            color: var(--rococo-text);
            opacity: 0.6;
            transition: all 0.3s;
        }

        .file-action-btn:hover {
            opacity: 1;
            color: var(--rococo-gold);
        }

        .right-panel {
            width: 60%;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            padding: 15px 30px;
            box-shadow: 0 2px 10px var(--rococo-shadow);
            display: flex;
            justify-content: space-between;
            align-items: center;
            backdrop-filter: blur(10px);
            position: relative;
            z-index: 100;
        }

        .header h1 {
            color: var(--rococo-text);
            font-size: 1.5rem;
            font-weight: 600;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .username {
            color: var(--rococo-text);
            font-size: 0.95rem;
        }

        .logout-btn {
            background: none;
            border: none;
            color: var(--rococo-text);
            cursor: pointer;
            padding: 8px 15px;
            border-radius: 6px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(212, 175, 55, 0.1);
            color: var(--rococo-gold);
        }

        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
            padding: 20px;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .message {
            display: flex;
            gap: 15px;
            max-width: 85%;
            animation: messageSlide 0.3s ease;
        }

        @keyframes messageSlide {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.user-message {
            margin-left: auto;
            flex-direction: row-reverse;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            flex-shrink: 0;
            box-shadow: 0 2px 8px var(--rococo-shadow);
        }

        .assistant-message .avatar {
            background: var(--rococo-gold);
            color: white;
        }

        .user-message .avatar {
            background: var(--rococo-purple);
            color: var(--rococo-text);
        }

        .message-content {
            background: white;
            padding: 15px 20px;
            border-radius: 15px;
            box-shadow: 0 2px 10px var(--rococo-shadow);
            position: relative;
            line-height: 1.6;
            color: var(--rococo-text);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .user-message .message-content {
            background: var(--rococo-purple);
            color: var(--rococo-text);
        }
        
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid var(--rococo-blue);
            border-top: 4px solid var(--rococo-gold);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .submit-button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, var(--rococo-gold) 0%, #C5A028 100%);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 15px;
            transition: background-color 0.3s;
        }

        .submit-button:hover {
            opacity: 0.9;
        }
        
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--rococo-shadow);
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>论文检测小助手</h1>
        <div class="user-info">
            <span class="username" id="username">加载中...</span>
            <button class="logout-btn" onclick="handleLogout()">退出登录</button>
        </div>
    </div>

    <div class="main-container">
        <!-- Left Panel -->
        <div class="left-panel panel">
            <!-- Upload Section -->
            <div class="upload-section" onclick="document.getElementById('fileInput').click()">
                <div>📄</div>
                <div>点击或拖拽文件到此处上传</div>
                <div style="font-size: 12px; opacity: 0.7;">支持 .doc, .docx, .pdf, .txt</div>
                <input type="file" id="fileInput" hidden accept=".doc,.docx,.pdf,.txt" onchange="handleFileSelect(event)">
            </div>
            
            <!-- File List -->
            <div class="panel-header">文件列表</div>
            <div class="file-list" id="fileListContainer">
                <!-- File items will be injected here -->
            </div>
        </div>

        <!-- Right Panel -->
        <div class="right-panel panel">
            <div class="chat-container">
                <div class="chat-messages" id="chatMessages">
                    <div class="message assistant-message">
                         <div class="avatar">AI</div>
                        <div class="message-content">
                            你好！我是论文检测小助手。请从左侧上传或选择一篇论文，我将为你进行分析，并在此处展示结果。
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>

    <script>
        let selectedFileId = null;

        function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
            }
        }

        async function fetchWithAuth(url, options = {}) {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
                throw new Error('No token found');
            }

            const headers = {
                ...options.headers,
                'Authorization': `Bearer ${token}`,
            };
            
            if (!(options.body instanceof FormData)) {
                headers['Content-Type'] = 'application/json';
            }

            try {
                const response = await fetch(url, { ...options, headers });
                if (response.status === 401) {
                    handleLogout();
                    throw new Error('Unauthorized');
                }
                return response;
            } catch (error) {
                console.error('Request failed:', error);
                throw error;
            }
        }

        window.onload = function() {
            checkAuth();
            const username = localStorage.getItem('username');
            if (username) {
                document.getElementById('username').textContent = username;
            }
            loadFileList();
        };

        function handleLogout() {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            window.location.href = 'login.html';
        }

        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }

        function hideLoading() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }

        async function loadFileList() {
            showLoading();
            try {
                const response = await fetchWithAuth('http://localhost:8080/api/paper/list');
                if (response.ok) {
                    const files = await response.json();
                    displayFileList(files);
                } else {
                    addMessageToChat('获取文件列表失败', 'assistant-message');
                }
            } catch (error) {
                console.error('获取文件列表失败:', error);
            } finally {
                hideLoading();
            }
        }

        function displayFileList(files) {
            const container = document.getElementById('fileListContainer');
            container.innerHTML = '';
            if (files.length === 0) {
                container.innerHTML = '<div style="text-align: center; color: var(--rococo-text); padding: 20px;">暂无文件</div>';
                return;
            }

            files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.dataset.fileId = file.id;
                fileItem.onclick = () => viewFileDetail(file.id);

                fileItem.innerHTML = `
                    <div class="file-info">
                        <div class="file-name">${file.fileName}</div>
                        <div class="file-meta">
                            ${new Date(file.uploadTime).toLocaleString()} - ${file.status}
                        </div>
                    </div>
                    <div class="file-actions">
                        <button class="file-action-btn" onclick="event.stopPropagation(); deleteFile(${file.id})">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/><path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/></svg>
                        </button>
                    </div>
                `;
                container.appendChild(fileItem);
            });
        }
        
        async function viewFileDetail(fileId) {
            // Highlight selected item
            document.querySelectorAll('.file-item').forEach(item => {
                item.classList.toggle('active', item.dataset.fileId == fileId);
            });
            
            showLoading();
            try {
                const response = await fetchWithAuth(`http://localhost:8080/api/paper/${fileId}`);
                if (!response.ok) throw new Error('Failed to fetch details');
                
                const fileDetail = await response.json();
                
                let resultHtml = '未找到分析结果。';
                if (fileDetail.status === '分析完成' || fileDetail.status === '已检测') {
                    if (fileDetail.aiRawOutput) {
                        resultHtml = marked.parse(fileDetail.aiRawOutput);
                    } else {
                        resultHtml = '分析已完成，但无文本报告内容。';
                    }
                } else {
                    resultHtml = `状态：${fileDetail.status}<br>请稍后再试。`;
                }

                const chatMessages = document.getElementById('chatMessages');
                chatMessages.innerHTML = ''; // Clear previous messages
                addMessageToChat(`正在查看文件: **${fileDetail.fileName}**`, 'user-message');
                addMessageToChat(resultHtml, 'assistant-message');

            } catch (error) {
                console.error('获取文件详情失败:', error);
                addMessageToChat('获取文件详情失败', 'assistant-message');
            } finally {
                hideLoading();
            }
        }

        async function deleteFile(fileId) {
            if (!confirm('确定要删除这个文件吗？此操作不可逆！')) return;

            showLoading();
            try {
                const response = await fetchWithAuth(`http://localhost:8080/api/paper/${fileId}`, { method: 'DELETE' });
                if (response.ok) {
                    addMessageToChat('文件删除成功', 'assistant-message');
                    loadFileList();
                } else {
                    throw new Error('删除文件失败');
                }
            } catch (error) {
                console.error('删除文件失败:', error);
                addMessageToChat('删除文件失败', 'assistant-message');
            } finally {
                hideLoading();
            }
        }

        async function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            showLoading();
            addMessageToChat(`正在上传文件: ${file.name}`, 'user-message');

            try {
                const response = await fetchWithAuth('http://localhost:8080/api/paper/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();

                if (response.ok) {
                    // 文件上传和分析成功，直接显示分析结果
                    addMessageToChat(`对 **${result.fileName}** 的分析已完成。`, 'assistant');

                    if (result.aiRawOutput) {
                        // aiRawOutput 包含 Markdown 格式的报告
                        addMessageToChat(result.aiRawOutput, 'assistant');
                    } else {
                        addMessageToChat('分析已完成，但未生成文本报告。您可以在左侧文件列表中查看其状态。', 'assistant');
                    }
                    
                    // 重新加载文件列表，显示新上传的文件及其状态
                    loadFileList();
                } else {
                    throw new Error(result.message || '上传失败');
                }
            } catch (error) {
                console.error('上传失败:', error);
                addMessageToChat(`上传失败: ${error.message}`, 'assistant');
            } finally {
                hideLoading();
                event.target.value = ''; // Reset file input
            }
        }
        
        function addMessageToChat(content, type) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            const avatarChar = type === 'user-message' ? '我' : 'AI';
            
            messageDiv.innerHTML = `
                <div class="avatar">${avatarChar}</div>
                <div class="message-content">${type === 'user-message' ? content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') : content}</div>
            `;
            
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // Drag and Drop
        const uploadSection = document.querySelector('.upload-section');
        uploadSection.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadSection.style.borderColor = 'var(--rococo-gold)';
        });
        uploadSection.addEventListener('dragleave', () => {
            uploadSection.style.borderColor = 'var(--border-color)';
        });
        uploadSection.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadSection.style.borderColor = 'var(--border-color)';
            if (e.dataTransfer.files.length > 0) {
                document.getElementById('fileInput').files = e.dataTransfer.files;
                handleFileSelect({ target: document.getElementById('fileInput') });
            }
        });
    </script>
</body>
</html>

